/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * GroupProcessorPanel.java
 *
 * Created on Jun 13, 2010, 1:25:09 PM
 */
package tp_imag.gui.group.processing;

import ij.ImagePlus;
import ij.io.FileSaver;
import java.awt.Component;
import java.awt.Cursor;

import java.awt.GridLayout;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.rmi.UnexpectedException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.naming.spi.DirectoryManager;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.filechooser.FileFilter;

import tp_imag.gui.MainPanel;
import tp_imag.gui.Tp_imagView;
import tp_imag.model.ImageItem;
import tp_imag.service.ServiceFactory;

import java.util.Vector;
import org.hibernate.Session;
import org.hibernate.Transaction;
import tp_imag.model.Fotografia;
import tp_imag.model.SSSelement;
import tp_imag.service.NewHibernateUtil;
import tp_imag.service.impl.CoordenadaTransformada;

/**
 *
 * @author LRinaudo
 */
public class GroupProcessorPanel extends javax.swing.JPanel {

    private int FIRST = 0;
    private int imagePointer;
    private String pager;
    private int pageNumber = 1;
    private int totalPages;
    org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(tp_imag.Tp_imagApp.class).getContext().getResourceMap(MainPanel.class);
    ArrayList<File> fileList;
    /* Lista de imagenes que se van a procesar para cargar en la base de datos */
    private List<ImageItem> imageList;
    private Tp_imagView mainForm;
    private ImgPreviewPanel previewPanel;

    /** Creates new form GroupProcessorPanel */
    /*public GroupProcessorPanel() {
    this.imagePointer = FIRST;
    initComponents();
    }*/
    public GroupProcessorPanel(Tp_imagView mainForm) {
        this.imagePointer = FIRST;
        initComponents();

        this.mainForm = mainForm;
        agregarPrevisualizacion();
        jProgressBar1.setVisible(false);
    }

    public void cleanAll() {
        this.jTextField1.setText("");
        this.imagePointer = FIRST;
        pageNumber = 1;
        imageList = null;
        previewPanel.cleanImages();
    }

    private void agregarPrevisualizacion() {
        jPanel3.setLayout(new GridLayout());

        previewPanel = new ImgPreviewPanel(this.mainForm);
        previewPanel.setVisible(true);
        jPanel3.add(previewPanel);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButton3 = new javax.swing.JButton();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jProgressBar1 = new javax.swing.JProgressBar();

        jPanel1.setName("jPanel1"); // NOI18N

        jButton3.setText("Procesar imágenes");
        jButton3.setName("jButton3"); // NOI18N
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ProcessAction(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(233, Short.MAX_VALUE)
                .addComponent(jButton3)
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jButton3, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 37, Short.MAX_VALUE)
        );

        jPanel2.setName("jPanel2"); // NOI18N

        jLabel1.setText("");
        jLabel1.setName("jLabel1"); // NOI18N

        jButton1.setText("Pag. siguiente");
        jButton1.setName("jButton1"); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
            	NextAction(evt);
            }
        });

        jButton2.setText("Pag. anterior");
        jButton2.setName("jButton2"); // NOI18N
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BackAction(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addContainerGap(180, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton2)
                .addGap(18, 18, 18)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 97, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 34, Short.MAX_VALUE)
                    .addComponent(jButton2)
                    .addComponent(jButton1)))
        );

        jPanel3.setBorder(new javax.swing.border.LineBorder(new java.awt.Color(0, 0, 0), 1, true));
        jPanel3.setName("jPanel3"); // NOI18N

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 768, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 97, Short.MAX_VALUE)
        );

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Seleccione la carpeta de imágenes"));
        jPanel4.setName("jPanel4"); // NOI18N

        jLabel2.setText("Directorio de origen:");
        jLabel2.setName("jLabel2"); // NOI18N

        jTextField1.setName("jTextField1"); // NOI18N

        jButton4.setText("Examinar");
        jButton4.setName("jButton4"); // NOI18N
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                BrowseAction(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 368, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jButton4)
                .addContainerGap(195, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addContainerGap(19, Short.MAX_VALUE)
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jButton4)))
        );

        jSeparator1.setName("jSeparator1"); // NOI18N

        jProgressBar1.setName("jProgressBar1"); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jSeparator1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 770, Short.MAX_VALUE)
                            .addComponent(jPanel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addContainerGap())
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 318, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 96, Short.MAX_VALUE)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel3, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(14, 14, 14)
                        .addComponent(jProgressBar1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void BackAction(java.awt.event.ActionEvent evt) {
        if (!(this.imagePointer == FIRST)) {
            this.imagePointer -= 16;
            --this.pageNumber;
            jLabel1.setText("Página " + this.pageNumber + " de " + this.totalPages);
            jLabel1.updateUI(); //jPanel2
            this.showBinariesImages();
        }
    }

    private void NextAction(ActionEvent evt) {
        if (this.imageList != null) {
            if (this.imagePointer + 16 < this.imageList.size()) {
                this.imagePointer += 16;
                ++this.pageNumber;
                jLabel1.setText("Página " + this.pageNumber + " de " + this.totalPages);
                this.setBinaryFilter();
                this.showBinariesImages();
            }
        }

    }

    private void initProgressBarForProcessAction() {
        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        jProgressBar1.setVisible(true);
        this.packFrame();
        jProgressBar1.setMaximum(this.imageList.size());
        jProgressBar1.setMinimum(0);
        jProgressBar1.setValue(0);
        Rectangle rec = new Rectangle(0, 0, 600, 600);
        jProgressBar1.paintImmediately(rec);
    }

    private void ProcessAction(java.awt.event.ActionEvent evt) {
        // TODO Auto-generated method stub -- OMAR: aca habria que poner lo que vos desarrollaste para procesar las imagenes.

        initProgressBarForProcessAction();

        // Primero: binarizo todas las imagenes que aun no esten binarizadas
        binarizeAllImages();
        generatePoints();
    }

    private void generatePoints() {
        Transaction tx = null;
        Rectangle rec = new Rectangle(0, 0, 600, 600);

        Session session = NewHibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();

        ArrayList<double[]> lista = new ArrayList<double[]>();
        for (int i = 0; i < this.imageList.size(); i++) {
            String pathBin = this.imageList.get(i).getBinarizedImagePath();
            BufferedImage image = ServiceFactory.getInstance().getImageProcessorService().openImage(pathBin);
            BufferedImage imagePoints = null;
            Vector<CoordenadaTransformada> vt = null;
            double[] vm = null;
            try {
                String path = this.imageList.get(i).getDirectory() + "\\" + "temp" + "\\" + this.imageList.get(i).getName();
                vt = ServiceFactory.getInstance().getImageProcessorService().vectorizeImage(image, path);

                /* A medida que se leen los contornos transformados se arma el indice
                 * Se calcula el modulo de cada componente en el vector transformado
                 * Luego se calcula la distancia euclidiana entre los vectores
                 */
                vm = ServiceFactory.getInstance().getMetricSpaceIndexService().CalcularModulo(vt);
                lista.add(vm);

            } catch (Exception ex) {
                ex.printStackTrace();
            }
            // obtengo un objeto ImagePlus de la imagen de puntos bufferedImage para poder utilizar en el fileSaver
            //ImagePlus imageDots = new ImagePlus();
            //imageDots.setImage(imagePoints);
            // guardo la imagen en un archivo temporal
            //FileSaver fileSaver = new FileSaver(imageDots);
            //fileSaver.saveAsJpeg(this.imageList.get(i).getDirectory() + "\\" + "temp" + "\\" + this.imageList.get(i).getName() + "Points" + ".jpg");
            Fotografia f = new Fotografia();
            f.setPathOriginal(this.imageList.get(i).getPath());
            f.setPuntosTf(transformarVector(vt));
            //session.save(f);

            //Voy cargando el elemento SSSElement qeu representa el modulo del vector transformado
            // y lo persisto en la base
            SSSelement sssElement = new SSSelement();
            sssElement.setValores(vm);
            sssElement.setPathOriginal(this.imageList.get(i).getPath());

            //sssElement.persist(sssElement);
            session.save(sssElement);


            jProgressBar1.setValue(i);
            jProgressBar1.paintImmediately(rec);
        }
        session.getTransaction().commit();

        try {
            session = NewHibernateUtil.getSessionFactory().getCurrentSession();
            tx = session.beginTransaction();
            List elementosGuardados = session.createQuery("select e from SSSelement as e order by id asc").list();
            for (Iterator iter = elementosGuardados.iterator(); iter.hasNext();) {
                SSSelement sssElement = (SSSelement) iter.next();
                lista.add(sssElement.getValores());
            }
            tx.commit();
        } catch (RuntimeException e) {
            // throw again the first exception
            throw e;
        }

        /*
         * Generar el indice
         */
        try {  //String fileName="C:\\Fotos\\indice.dat";
            ServiceFactory.getInstance().getMetricSpaceIndexService().buildIndex(lista);
            //ServiceFactory.getInstance().getMetricSpaceIndexService().save(fileName);
            } catch (Exception ex) {
            ex.printStackTrace();
        }

        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        jProgressBar1.setVisible(false);
    }

    private String transformarVector(Vector<CoordenadaTransformada> vector) {
        String resultado = "";
        for (Iterator<CoordenadaTransformada> it = vector.iterator(); it.hasNext();) {
            CoordenadaTransformada coordenadaTransformada = it.next();
            resultado += coordenadaTransformada.getX() + "," + coordenadaTransformada.getY() + ";";
        }
        return resultado;
    }

    private void binarizeAllImages() {
        for (int i = 0; i < this.imageList.size(); i++) {
            if (!this.imageList.get(i).isImageBinarized()) {
                setBinaryFilterToImage(this.imageList.get(i));
            }
        }

    }

    private void BrowseAction(java.awt.event.ActionEvent evt) {
        JFileChooser chooser = new JFileChooser();
        chooser.setFileSelectionMode(JFileChooser.FILES_AND_DIRECTORIES);
        chooser.setMultiSelectionEnabled(true);
        FileFilter fileFilter = new FileFilter() {

            @Override
            public boolean accept(File file) {
                return file.getAbsolutePath().endsWith(".jpg") || file.isDirectory() || file.getAbsolutePath().endsWith(".JPG");
            }

            @Override
            public String getDescription() {
                return "jpg settings files";
            }
        };


        chooser.setFileFilter(fileFilter);
        int returnVal = chooser.showOpenDialog(this);
        try {
            if (returnVal == JFileChooser.APPROVE_OPTION) {

                if (chooser.getSelectedFile().isDirectory()) {
                    jTextField1.setText(chooser.getSelectedFile().getPath());
                    String[] filesName = chooser.getSelectedFile().list();
                    this.imageList = getImageList(chooser.getSelectedFile().getAbsolutePath(), filesName);
                    if (imageList.size() > 0) {
                        if (!directoryBinExist(this.imageList.get(0).getDirectory())) {
                            createBinDirectory();
                        }
                    }
                } else {
                    File[] files = chooser.getSelectedFiles();
                    this.imageList = transform(files);
                    if (imageList.size() > 0) {
                        if (!directoryBinExist(this.imageList.get(0).getDirectory())) {
                            createBinDirectory();
                        }
                    }
                    jTextField1.setText(files[0].getAbsolutePath());
                }
                defineTotalNumberOfPages();
            }

            setBinaryFilter();
            showBinariesImages();
            jLabel1.setText("Página 1 de " + this.totalPages);
        } catch (RuntimeException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void defineTotalNumberOfPages() {
        double decimalTotalPages = this.imageList.size() / 16.0;
        this.totalPages = (int) (this.imageList.size() / 16);
        if (decimalTotalPages > this.totalPages) {
            this.totalPages += 1;
        }
    }

    private boolean directoryBinExist(String fileName) {
        File file1 = new File(fileName + "\\" + "temp");
        File file2 = new File(fileName + "\\" + "Temp");
        if (file1.exists() || file2.exists()) {
            return true;
        }
        return false;
    }

    private void createBinDirectory() {
        if (this.imageList.size() > 0) {
            String path = this.imageList.get(0).getDirectory();
            try {
                boolean success = (new File(path + "\\" + "temp").mkdir());

            } catch (Exception e) {
                // TODO: handle exception
            }
        }
    }

    /**
     * Refresca la las imagenes de la pagina actual
     */
    public void showBinariesImages() {
        previewPanel.refreshImages(getImageListToShow());

        packFrame();
    }

    private void packFrame() {
        Component comp = this;
        while (!(comp instanceof JFrame)) {
            comp = comp.getParent();
        }
        ((JFrame) comp).repaint();
        ((JFrame) comp).validate();
    }

    private List<ImageItem> getImageListToShow() {
        List<ImageItem> listToShow = new ArrayList<ImageItem>();
        int maxToShow = getImageToShow();
        for (int i = imagePointer; i < maxToShow; i++) {
            listToShow.add(imageList.get(i));
        }

        return listToShow;
    }

    private int getImageToShow() {
        /*
        int imageToShow = 16;
        if (this.imagePointer + 16 > this.imageList.size()){
        imageToShow = this.imageList.size();
        }
         *
         */
        int imageToShow = 0;
        if (this.imageList.size() < (pageNumber * 16)) {
            imageToShow = this.imageList.size();
        } else {
            imageToShow = (pageNumber * 16);
        }

        return imageToShow;
    }

    private void setBinaryFilter() {
        int imageToShow = getImageToShow();

        final int maxToShow = imageToShow;

        setCursor(new Cursor(Cursor.WAIT_CURSOR));
        Rectangle rec = new Rectangle(0, 0, 600, 600);
        jProgressBar1.setVisible(true);
        this.packFrame();


        jProgressBar1.setMaximum(maxToShow - 1);
        jProgressBar1.setMinimum(this.imagePointer);

        for (int i = this.imagePointer; i < imageToShow; i++) {
            final int percent = i;


            if (!this.imageList.get(i).isImageBinarized()) {
                setBinaryFilterToImage(this.imageList.get(i));
                this.imageList.get(i).setImageBinarized(true);
            }

            jProgressBar1.setValue(percent + 1);
            jProgressBar1.paintImmediately(rec);
        }

        setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
        jProgressBar1.setVisible(false);

    }

    private void setBinaryFilterToImage(ImageItem imageItem) {
        //obtengo la imagen binarizada
        BufferedImage image = ServiceFactory.getInstance().getImageProcessorService().openImage(imageItem.getPath());
        BufferedImage imageBinarized = ServiceFactory.getInstance().getImageProcessorService().binarizeImage(image);
        // obtengo un objeto ImagePlus de la imagen binarizada bufferedImage para poder utilizar en el fileSaver
        ImagePlus imageBin = new ImagePlus();
        imageBin.setImage(imageBinarized);
        // guardo la imagen en un archivo temporal
        FileSaver fileSaver = new FileSaver(imageBin);
        fileSaver.saveAsJpeg(imageItem.getDirectory() + "\\" + "temp" + "\\" + imageItem.getName() + "Bin" + ".jpg");
        imageItem.setImageBinarized(true);
    }

    private ArrayList<ImageItem> transform(File[] files) throws IOException {
        ArrayList<ImageItem> imageList = new ArrayList<ImageItem>();
        for (int i = 0; i < files.length; i++) {
            int position = files[i].getCanonicalPath().lastIndexOf("\\");
            String directory = files[i].getCanonicalPath().substring(0, position);
            String name = files[i].getCanonicalPath().substring(position + 1);
            ImageItem imageItem = new ImageItem(directory, name);
            imageList.add(imageItem);
        }
        return imageList;
    }

    private ArrayList<ImageItem> getImageList(String absolutePath, String[] filesName) {
        ArrayList<ImageItem> imageList = new ArrayList<ImageItem>();
        for (int i = 0; i < filesName.length; i++) {
            if (filesName[i].contains(".")) {
                ImageItem imageItem = new ImageItem(absolutePath, filesName[i]);
                if (filesName[i].matches(".*\\.jpg") || filesName[i].matches(".*\\.JPG")) {
                    imageList.add(imageItem);
                }
            }
        }
        return imageList;
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JProgressBar jProgressBar1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration//GEN-END:variables
}
